package com.delu.PhoneMessage;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Controller
public class PhoneMessageServiceImpl {
    @Autowired
    private RedisTemplate redisTemplate;
    public void getPhoneMessage(String phoneNum) {
        Client client = null;
        try {
            client = createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 调用工具类 获取随机验证码(6位,纯数字)
                String code = RandomStringUtils.randomNumeric(6);

                //将用户手机号以及发送的短信放进redis,设置30分钟过期时间
                redisTemplate.boundValueOps(phoneNum).set(code);
                //设置验证码过期为30分钟
                redisTemplate.expire(phoneNum,1, TimeUnit.MINUTES);

                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNum) //手机号
                .setSignName("东科创想") //签名
                .setTemplateCode("SMS_162522027") //模板名字
                .setTemplateParam("{\"sms_code\":\"" + code + "\"}"); //模板需要的变量
                 System.out.println(code);
                System.out.println("发送成功");
        // 复制代码运行请自行打印 API 的返回值
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            SendSmsResponseBody body = sendSmsResponse.getBody();
            System.out.println("阿里云的返回码:" + body.code);
            System.out.println("阿里云的返回消息:" + body.message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

}
